import axios from "axios";
import React from "react";
import "antd/dist/antd.css";
import {
  Form,
  Table,
  Space,
  Button,
  Select,
  Input,
  Modal,
  message,
  Upload
} from "antd";
import myAxios from "../service/myAxios";
import { CloudDownloadOutlined ,UploadOutlined} from "@ant-design/icons";

const { Option } = Select;
const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};
const { confirm } = Modal;

class ShowUser extends React.Component {
  constructor(props) {
    super(props);
    // 定义 state
    this.state = {
      id: 0,
      dataSources: [],
      pageNum: 1,
      pageSize: 7,
      total: 0,
      username: "",
      name: "",
      sex: "",
      mid: 0,
      musername: "",
      mpassword: "",
      mname: "",
      msex: "",
      visible: false,
      selectedRowKeys: [],
    };
    this.formRef = React.createRef();
  }

  columns = [
    {
      title: "编号",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "password",
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "性别",
      dataIndex: "sex",
      key: "sex",
      render: (sex) => {
        if (sex == "1") {
          return "男";
        }
        return "女";
      },
    },
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              this.showModal(record);
            }}
          >
            {" "}
            编辑
          </a>
          <a
            onClick={() => {
              this.del(record);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];
  // 对话框开始
  handleClick = () => {
    this.formRef.current
      .validateFields()
      .then((values) => {
        console.log(values);
        const user = {
          id: this.state.mid,
          username: values.username,
          password: values.password,
          name: values.name,
          sex: values.sex,
        };
        myAxios.post("test/updateUser", user).then((data) => {
          if (data.code === 4001) {
            message.success(data.message);
          }
          this.hideModal();
        });
      })
      .catch((e) => {
        console.log(e);
      });
  };

  showModal = (record) => {
    const params ={params : record.id}
    myAxios.get("test/findUserById/", params).then((data) => {
      if (data.code === 1001) {

        this.setState({
          visible: true,
          mid: record.id,
        })
      setTimeout(()=>{
        this.formRef.current.setFieldsValue({
          username: data.data.username,
          password: data.data.password,
          name: data.data.name,
          sex: data.data.sex,
        });
      },100)


      }
    });
  };

  hideModal = () => {
    this.setState({ visible: false });
    const pageVO = {
      pageNum: this.state.pageNum,
      pageSize: this.state.pageSize,
      username: this.state.username,
      name: this.state.name,
      sex: this.state.sex,
    };
    // 后端请求数据
    this.questData(pageVO);
  };

  //用户删除
  del = (record) => {
    confirm({
      title: "是否确定删除该数据?",
      content: "点击确定后该行数据将被删除",
      okText:"删除",
      cancelText:"取消",
      onOk: () => {
        myAxios.delete("test/delUserById/",{id: record.id}).then((data) => {
          if (data.code === 3001) {
            message.success(data.message);
          }
          this.onSearch();
        });
      },
      onCancel() {
        console.log("取消操作");
      },
    });
  };

  questData = (pageVO) => {
    myAxios.post("test/searchUser", pageVO).then((data) => {
      if (data.code === 1001) {
        const total = data.data.total;
        const userlist = data.data.data.map((d) => {
          d.key = d.id;
          return d;
        });
        this.setState({
          total: total,
          dataSources: userlist,
        });
      }
    });
  };

  //初始化数据
  componentDidMount() {
    const pageVO = {
      pageNum: this.state.pageNum,
      pageSize: this.state.pageSize,
      username: this.state.username,
      name: this.state.name,
      sex: this.state.sex,
    };
    // 后端返回数据和总条数
    this.questData(pageVO);
  }

  handleSex = (e) => {
    this.setState({ sex: e.target.value });
  };
  //向后端请求检索数据
  onSearch = () => {
    // 每次搜索重新设置页面
    this.setState({ pageNum: 1 });
    const pageVO = {
      pageNum: 1,
      pageSize: this.state.pageSize,
      username: this.state.username,
      name: this.state.name,
      sex: this.state.sex,
    };
    // 后端请求数据
    this.questData(pageVO);
  };

  //发送下载请求
  download = () => {
    if (this.state.selectedRowKeys.length > 0) {
      myAxios.download("test/download2", this.state.selectedRowKeys,"用户信息表.xls");
    } else {
      
     const  data ={
        username: this.state.username,
        name: this.state.name,
        sex: this.state.sex,
      };
      myAxios.download("test/download", data,"用户信息表.xlsx");
    }
  };

  //选择框
  onSelectChange = (selectedRowKeys) => this.setState({ selectedRowKeys });
  

  databasebackup = () => {
    console.log("object");
    const res = axios
      .request({
        url: "http://localhost:8081/test/databasebackup",
        headers: {
          Authorization: "Bearer " + window.localStorage.getItem("adminToken"),
        },
        method: "post",
      })
      .then((res) => {
        if (res.status === 200) {
          if (res.data == "success")  message.success("备份成功");
          else message.error("备份失败");
        }
      });
  };

  uploadChange=(info) =>{
    if (info.file.status !== '文件导入中') {
      console.log( '文件导入中');
    }
    if (info.file.status === 'done') 
    {
      console.log(info.file.response)
      if  (info.file.response.code === 2001)     message.success(info.file.response.message);
      else  message.error(info.file.response.message);

    } else if (info.file.status === 'error')
     {
      message.error(`${info.file.name} 文件上传失败.`);
    }
    
    this.onSearch()
  }


  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <div className="App">
        <Form layout={"inline"}>
          <Form.Item label="按用户名">
            <Input
              value={this.state.username}
              placeholder="输入查找用户名关键字"
              onChange={(e) => {
                const val = e.target.value;
                this.setState({
                  username: val,
                });
              }}
            />
          </Form.Item>

          <Form.Item label="按姓名">
            <Input
              value={this.state.name}
              placeholder="输入查找昵称关键字"
              onChange={(e) => {
                const val = e.target.value;
                this.setState({
                  name: val,
                });
              }}
            />
          </Form.Item>
          <Form.Item>
            <Select
              defaultValue="全部"
              style={{ width: 120 }}
              value={this.state.sex}
              onChange={(value) => {
                const val = value;
                console.log(val);
                this.setState({
                  sex: val,
                });
              }}
            >
              <Option value="">全部</Option>
              <Option value={1}>男</Option>
              <Option value={2}>女</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button onClick={this.onSearch} type="primary">
              查询
            </Button>
          </Form.Item>
        </Form>
        <br />
        <div>
          <Button onClick={this.download} icon={<CloudDownloadOutlined />}>
            下载数据
          </Button>
          &nbsp;&nbsp;
          <Upload
              name="files"
              action="http://localhost:8081/file/exclUpload"
              onChange={this.uploadChange}
              method="POST"
              maxCount={1}
              headers= {{			Authorization: "Bearer " +window.localStorage.getItem("adminToken")}
              
		}
        >
              <Button icon={<UploadOutlined />}>导入Excel</Button>
        </Upload>
        </div>

        <Table
          rowSelection={rowSelection}
          dataSource={this.state.dataSources}
          columns={this.columns}
          pagination={{
            defaultCurrent: 1,
            current: this.state.pageNum,
            total: this.state.total,
            pageSize: this.state.pageSize,
            showTotal: (total) => {
              return `总共${total}条`;
            },
            onChange: (page, pageSize) => {
              //把当前页数据保存下来作为参数

              this.setState({
                pageSize: pageSize,
                pageNum: page,
              });
              const pageVO = {
                pageNum: page,
                pageSize: pageSize,
                username: this.state.username,
                name: this.state.name,
                sex: this.state.sex,
              };
              // 后端请求数据
              this.questData(pageVO);
            },
          }}
        />
        <Modal
          title="Modal"
          visible={this.state.visible}
          onOk={this.hideModal}
          onCancel={this.hideModal}
          // destroyOnClose={true}
          footer={[]}
        >
          <Form {...layout} ref={this.formRef}>
            <Form.Item
              name={"username"}
              label={"用户名"}
              rules={[
                {
                  required: true,
                  message: "用户名必须填写",
                },
              ]}
            >
              <Input placeholder="请填写用户名" style={{ width: "200px" }} />
            </Form.Item>
            <Form.Item
              name={"password"}
              label={"密码"}
              rules={[
                {
                  required: true,
                  message: "密码必须填写",
                },
              ]}
            >
              <Input placeholder="请填写名称" style={{ width: "200px" }} />
            </Form.Item>
            <Form.Item
              // initialValue={this.state.mname}
              name={"name"}
              label={"名称"}
              rules={[
                {
                  required: true,
                  message: "密码必须填写",
                },
              ]}
            >
              <Input placeholder="请填写密码" style={{ width: "200px" }} />
            </Form.Item>

            <Form.Item
              // initialValue={this.state.msex}
              name={"sex"}
              label={"性别"}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select allowClear style={{ width: "200px" }}>
                <Option value="1">男</Option>
                <Option value="2">女</Option>
              </Select>
            </Form.Item>

            <Form.Item {...tailLayout}>
              <Button onClick={this.handleClick}>确定更改</Button>

              <Button type="link" htmlType="button" onClick={this.hideModal}>
                取消操作
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default ShowUser;
